package com.yangmin.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLoadBalance implements LoadBalance {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    // 获取实例对象
    @Override
    public ServiceInstance getInstance(List<ServiceInstance> serviceInstanceList) {
        int size = serviceInstanceList.size();
        int index = getNext() % size;
        return serviceInstanceList.get(index);
    }

    // 获取当前请求次数
    public final Integer getNext() {
        int current;
        int next;
        do {
            current = atomicInteger.get();
            next = current > Integer.MAX_VALUE ? 0 : current + 1;
            System.out.println("请求第" + next + "次");
        } while (!this.atomicInteger.compareAndSet(current, next));
        return next;
    }
}
